import React, { useState, useRef, useEffect, forwardRef } from 'react';
import { Form, Button, Upload, Card, message } from 'antd';
import { UploadOutlined, ToolOutlined, EnvironmentTwoTone } from '@ant-design/icons';
import { DndProvider } from 'react-dnd'
import { withRouter,Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { SourceBox, TargetBox, DragNode } from '&components/dragNode';
import { EQUIPMENT_TYPE } from './constants';

import styles from './styles.module.less';
import { Label } from '_bizcharts@3.5.9@bizcharts';
let BMap = window.BMap;

const mapStateToProps = (state) => ({ backImgList:state.equipmentPage.backImgList});
const mapDispatchToProps = dispatch => {
  return {
    getBackImg: dispatch.equipmentPage.getBackImg,
    setIndex: dispatch.equipmentPage.setState,
    getCurve: dispatch.equipmentPage.getCurve,
    getAverageRate: dispatch.equipmentPage.getAverageRate,
    setChoice: dispatch.equipmentPage.setState,
    get2DAnd3D: dispatch.equipmentPage.get2DAnd3D,
    setPosition: dispatch.setFSMMessagePage.setState,
  }
};

// 创建图标
let blueIcon = new BMap.Icon("http://api.map.baidu.com/lbsapi/creatmap/images/us_mk_icon.png", new BMap.Size(23, 25), {
  offset: new BMap.Size(10, 2), // 指定定位位置
  imageOffset: new BMap.Size(0 - 1 * 23, 0 - 1 * 22.5) // 设置图片偏移使用左侧的图片
//  imageOffset: new BMap.Size(-20, 0 - 1 * 25) // 设置图片偏移使用右侧的图片0-x*25代表使用第x+1张图片
});
let redIcon = new BMap.Icon("http://api.map.baidu.com/lbsapi/creatmap/images/us_mk_icon.png", new BMap.Size(23, 25), {
  offset: new BMap.Size(10, 2), // 指定定位位置
  imageOffset: new BMap.Size(0 - 2 * 23, 0 - 1 * 22.5) // 设置图片偏移使用左侧的图片
//  imageOffset: new BMap.Size(-20, 0 - 1 * 25) // 设置图片偏移使用右侧的图片0-x*25代表使用第x+1张图片
});
let greenIcon = new BMap.Icon("http://api.map.baidu.com/lbsapi/creatmap/images/us_mk_icon.png", new BMap.Size(23, 25), {
  offset: new BMap.Size(10, 2), // 指定定位位置
  imageOffset: new BMap.Size(0 - 0 * 23, 0 - 1 * 22.5) // 设置图片偏移使用左侧的图片
//  imageOffset: new BMap.Size(-20, 0 - 1 * 25) // 设置图片偏移使用右侧的图片0-x*25代表使用第x+1张图片
});
let map = {};
const newHotMap = (props) => {
    const mapRef = useRef();
    const [status, setStatus] = useState(false)
    const [equip1, setEquip1] = useState({})
    const [equip2, setEquip2] = useState({})
    const [equip3, setEquip3] = useState({})
    const [equip4, setEquip4] = useState({})

    // const uploadFile = (e) => {
    //     const file = e.fileList[1] ? e.fileList[1] : e.fileList[0];
    //     setFileList([file]);
    // };

    // const [fileList, setFileList] = useState([]);

    const renderDepartments = () => {
        const departmentList = [
            {
                img: 'https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png',
                text: 'FSM',
                color: 'blue',
                type: EQUIPMENT_TYPE.FSM
            },
            {
                img: 'https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png',
                text: 'PZT',
                color: 'green',
                type: EQUIPMENT_TYPE.PZT
            },
            {
                img: 'https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png',
                color: 'red',
                text: 'EMAT',
                type: EQUIPMENT_TYPE.EMAT
            }
        ];
        return departmentList.map((i, key) => (
            <SourceBox key={ key } type={ i.type }>
                <div className={ styles.card }  onClick={() => handlePointClick(i.type)}>
                    {/* <img className={ styles.cardImg } src={ i.img } alt={ i.text }/> */}
                    <EnvironmentTwoTone  style={{fontSize: '30px'}}  twoToneColor={i.color} />
                    <div className={ styles.cardText }>{ i.text }</div>
                </div>
            </SourceBox>
        ));
    };

    const accept = [ EQUIPMENT_TYPE.PZT, EQUIPMENT_TYPE.EMAT, EQUIPMENT_TYPE.FSM ];

    const renderItems = (props) => {
        return (
            <DragNode { ...props }>

            </DragNode>
        )
    };
    // const rightClickMarker = (marker,point,backImg,index,equipIndex) => {
    //   const { history, location, setIndex, getCurve, setChoice, getAverageRate, get2DAnd3D} = props;
    //   const equip = props.backImgList[index].backImgVo2s[equipIndex];
    //   var watchDataMarker = function (e, ee, marker) {  
    //     // console.log(e+','+ee);
    //     // console.log(backImg);
    //     // console.log(equipIndex);
    //     setIndex({index:index})
    //     setIndex({equipIndex:equipIndex})
    //     setEquip1({
    //         equipId: equip.equipId,
    //         type:1,
    //         choice:0,
    //     })
    //     setEquip2({
    //         equipId: equip.equipId,
    //         type:2,
    //         choice:0,
    //     })
    //     setEquip3({
    //         equipId: equip.equipId,
    //         type:3,
    //         choice:0,
    //     })
    //     setEquip4({
    //         equipId: equip.equipId,
    //         type:4,
    //         choice:0,
    //     })
    //     equip.choice = 0
    //     const curveEquip = {
    //       equipId:equip.equipId,
    //       type:1,
    //       time:'newTime',
    //       choice:0
    //     }
    //     setChoice({optionData:{}})
    //     setChoice({equip:equip})
    //     getCurve(equip)
    //     getAverageRate(equip)
    //     setChoice({choice:'all'})
    //     setChoice({width:500,height:432})
    //     get2DAnd3D(equip1)
    //     get2DAnd3D(equip2)
    //     get2DAnd3D(equip3)
    //     get2DAnd3D(equip4)
    //     location.pathname = '/FSM/' + backImg.id;
    //     history.push(location);
    //   }
    //   var watchInfoMarker = function (e,ee,marker) {  
    //     console.log(e);
    //   }
    //   var watchLtDataMarker = function (e,ee,marker) {  //查看壁厚损失
    //     // console.log(ee);
    //     const curveEquip = {
    //       equipId: equip.equipId,
    //       type:1,
    //       time:'newTime',
    //       choice:1,
    //     }
    //     equip.choice = 1;
    //     setChoice({optionData:{}})
    //     setChoice({equip:equip})
    //     getCurve(equip)
    //     setIndex({index:index})
    //     setIndex({equipIndex:equipIndex})
    //     setChoice({choice:'lt'})
    //     setChoice({width:980,height:600})
    //     location.pathname = '/FSM/' + backImg.id;
    //     history.push(location);
    //   }
    //   var watchRtDataMarker = function (e,ee,marker) {   //剩余壁厚
    //     const curveEquip = {
    //       equipId: equip.equipId,
    //       type:1,
    //       time:'newTime',
    //       choice:2,
    //     }
    //     equip.choice = 2;
    //     setChoice({optionData:{}})
    //     setChoice({equip:equip})
    //     getCurve(equip)
    //     setIndex({index:index})
    //     setIndex({equipIndex:equipIndex})
    //     setChoice({choice:'rt'})
    //     setChoice({width:980,height:600})
    //     location.pathname = '/FSM/' + backImg.id;
    //     history.push(location);
    //   }
    //   var watchSvDataMarker = function (e,ee,marker) {  
    //     // console.log(ee);
    //     const curveEquip = {
    //       equipId: equip.equipId,
    //       type:1,
    //       time:'newTime',
    //       choice:3,
    //     }
    //     equip.choice = 3;
    //     setChoice({optionData:{}})
    //     setChoice({equip:equip})
    //     getCurve(equip)
    //     setIndex({index:index})
    //     setIndex({equipIndex:equipIndex})
    //     setChoice({choice:'sv'})
    //     setChoice({width:980,height:600})
    //     location.pathname = '/FSM/' + backImg.id;
    //     history.push(location);
    //   }
    //   var watchAvgDataMarker = function (e,ee,marker) {  
    //     // console.log(ee);
    //     equip.choice = 0;
    //     getAverageRate(equip)
    //     setIndex({index:index})
    //     setIndex({equipIndex:equipIndex})
    //     setChoice({choice:'avgRate'})
    //     setChoice({width:980,height:600})
    //     location.pathname = '/FSM/' + backImg.id;
    //     history.push(location);
    //   }
    //   var markerMenu = new BMap.ContextMenu();
    //   markerMenu.addItem(new BMap.MenuItem('查看设备信息',watchInfoMarker.bind(marker)))
    //   markerMenu.addItem(new BMap.MenuItem('查看设备数据',watchDataMarker.bind(marker)))
    //   markerMenu.addItem(new BMap.MenuItem('查看壁厚损失',watchLtDataMarker.bind(marker)))
    //   markerMenu.addItem(new BMap.MenuItem('查看剩余壁厚',watchRtDataMarker.bind(marker)))
    //   markerMenu.addItem(new BMap.MenuItem('查看损失速率',watchSvDataMarker.bind(marker)))
    //   markerMenu.addItem(new BMap.MenuItem('查看平均损失速率',watchAvgDataMarker.bind(marker)))
    //   marker.addContextMenu(markerMenu)
    // }
    const getMap = () => {
        map = new BMap.Map("allMap",{mapType: BMAP_HYBRID_MAP}); // 创建Map实例
        map.centerAndZoom("北京", 9); // 初始化地图,设置中心点坐标和地图级别
        map.addControl(new BMap.MapTypeControl()); //添加地图类型控件
        map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
        map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
        
        // console.log(props);
        if (props.backImgList) {
          props.backImgList.map((item, index) => {
            item.backImgVo2s.map((equip,equipIndex) => {
              var pt = new BMap.Point(equip.x,equip.y);
              var marker = new BMap.Marker(pt, {
                icon: equip.type === 'FSM' ? blueIcon : redIcon
              })
              map.addOverlay(marker)
              // rightClickMarker(marker, pt, item.backImgVO1, index, equipIndex)
            })
          })
        }
        // 创建Marker标注，图标
        // var pt1 = new BMap.Point(114.513, 39.409);
        // var marker1 = new BMap.Marker(pt1, {
        //     icon: blueIcon
        // });
        // var pt2 = new BMap.Point(115.317, 39.909);
        // var marker2 = new BMap.Marker(pt2, {
        //     icon: redIcon
        // });
        // var pt3 = new BMap.Point(117.417, 40.309);
        // var marker3 = new BMap.Marker(pt3, {
        //     icon: greenIcon
        // });
        // var pt4 = new BMap.Point(116.417, 39.309);
        // var marker4 = new BMap.Marker(pt4, {
        //     icon: blueIcon
        // });
        // 创建点标记
        // var marker1 = new BMap.Marker(new BMap.Point(116.404, 39.925));
        // var marker2 = new BMap.Marker(new BMap.Point(116.404, 39.915));
        // var marker3 = new BMap.Marker(new BMap.Point(116.395, 39.935));
        // var marker4 = new BMap.Marker(new BMap.Point(116.415, 39.931));
        // 在地图上添加点标记
        // map.addOverlay(marker1);
        // map.addOverlay(marker2);
        // map.addOverlay(marker3);
        // map.addOverlay(marker4);
        // //点击事件
        // marker1.addEventListener('click', function () {
        //   console.log("测试")
        // });
        // marker2.addEventListener('click', function () {
        //   console.log("测试")
        // });
        // marker3.addEventListener('click', function () {
        //   console.log("测试")
        // });
        // marker4.addEventListener('click', function () {
        //   console.log("测试")
        // });
        // rightClickMarker(marker1,pt1)
        // rightClickMarker(marker2,pt2)
        // rightClickMarker(marker3,pt3)
        // rightClickMarker(marker4,pt4)
    };
    
    const newRightClickMarker = (marker, pt, x, y) => {
      console.log(x,y);
    }

    const handlePointClick = (type) => {
      const {location, history, setChoice} = props
      console.log(type);
      if (!status) {
        setStatus(true); //添加请求完成再设为false
        var tempPt = new BMap.Point(116.404, 39.9);
        let icon;
        if (type == 'FSM') {
          icon = blueIcon
        } else if (type == 'EMAT') {
          icon = redIcon
        } else {
          icon = greenIcon 
        }
        var tempMarker = new BMap.Marker(tempPt, {
              icon: icon
        });
        var opts = {
          width: 150,
          height: 50,
          title: ''
        }
        var infoWindow = new BMap.InfoWindow("拖拽放置图标位置，左键添加设备详细信息",opts)
        tempMarker.enableDragging();
        let x = 0,y = 0;
        tempMarker.addEventListener("dragend", function (e) {  
          console.log("当前位置：" + e.point.lng + "," + e.point.lat); //redux
          let newEquipPosition = {
            x:e.point.lng,
            y:e.point.lat,
          }
          props.setChoice({
            newEquipPosition:newEquipPosition
          })
        })
        tempMarker.addEventListener('click', function () {  
          location.search = type
          if( type == 'FSM' ) {
            props.setPosition({status: 'add'})
            location.pathname = '/admin/setFsmMessage'
            history.push(location);
          } else {
            location.pathname = '/admin/setUtMessage'
            history.push(location)
          }
        })
        map.addOverlay(tempMarker)
        map.openInfoWindow(infoWindow, tempPt)
        
      } else {
        message.error('清先完善前一个设备信息')
      }
    }

    useEffect(() => {
      getMap();
    }, []);
    return (
        <DndProvider backend={ HTML5Backend }>
            <div className={ styles.container }>
                <div className={ styles.canvas }>
                    <div ref={ mapRef } className={ styles.map }>
                        {/* {getMap()} */}
                        <div
                          id='allMap'
                          style={{
                            width:'80vw',
                            height:'69vh'
                        }} />
                    </div>
                        <TargetBox accept={ accept } renderItem={ renderItems }/>
                    <div className={ styles.tools }>
                        <Form>
                            {/* <Form.Item>
                                <div className={ styles.title }>
                                    <ToolOutlined />
                                    工具栏
                                </div>
                                <Upload accept={['image/jpeg']} fileList={ fileList } onChange={ uploadFile }>
                                    <Button icon={<UploadOutlined />}>上传背景图</Button>
                                </Upload>
                            </Form.Item> */}
                            <Form.Item>
                                <div className={ styles.title }>
                                    <ToolOutlined/>
                                    设备列表
                                </div>
                                <div className={ styles.cards } >
                                    { renderDepartments() }
                                </div>
                            </Form.Item>
                            <Form.Item>
                                <Button className={ styles.btn }>提交</Button>
                            </Form.Item>
                        </Form>
                    </div>
                </div>
            </div>
        </DndProvider>
    );
}
export default connect(mapStateToProps,mapDispatchToProps)(withRouter(newHotMap))
